package com.haibo.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.haibo.entity.dto.PreConsultationHospitalDTO;
import com.haibo.utils.EncryptUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : 刘海波
 * @Date: 2025-08-11 19:23
 * @Description:
 */
@Slf4j
@RequestMapping("/api/v1")
@RestController
public class MiddleController {

    @Value(value = "${hitales.pre.productSecret}")
    public String productSecret;
    @Value(value = "${hitales.pre.mustEncrypt}")
    public Boolean mustEncrypt;

    @GetMapping("/helloWorld")
    public String helloWorld() {
        return "Hello World! " + LocalDateTime.now();
    }

    @GetMapping("/redirect")
    public void redirect(HttpServletRequest request, HttpServletResponse response) {
        String redirectParam = request.getQueryString();
        if (StringUtils.isBlank(redirectParam)) {
            log.error("[预问诊重定向]请求参数为空!");
            return;
        }
        if (!mustEncrypt) {// 不加密
            log.info("[预问诊重定向]不加密，原始请求参数：{}", redirectParam);
        } else { // 加密
            log.info("[预问诊重定向]加密，原始请求参数：{}", redirectParam);
            String decodedUrlParam = EncryptUtil.decryData2String(redirectParam,productSecret);
            // openid=oFWrAt78xcXaUXhxDf9eTsiV772E&patient_id=11262296
            log.info("[预问诊重定向]加密，解密后的请求参数：{}", decodedUrlParam);
            Map<String, String> paramMap = new HashMap<>();
            String[] paramPairs = decodedUrlParam.split("&");

            for (String pair : paramPairs) {
                String[] pairArray = pair.split("=");
                paramMap.put(pairArray[0],pairArray[1]);
            }
            log.info("[预问诊重定向]加密，解密后的请求参数json：{}", JSON.toJSONString(paramMap));
            PreConsultationHospitalDTO hospitalDTO = JSONObject.parseObject(JSON.toJSONString(paramMap),PreConsultationHospitalDTO.class);
            System.out.println("hospitalDTO = " + hospitalDTO);
        }
    }

}
